package com.kundi.dooradmin.controller;

import com.kundi.dooradmin.entity.Introduction;
import com.kundi.dooradmin.service.IntroductionService;
import com.kundi.dooradmin.util.MapUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

/**
 * Author 赵恒
 * Date 2020/7/9
 */
@Controller
@RequestMapping("/introduction")
public class IntroductionController {
    @Resource
    IntroductionService introductionService;

    @RequestMapping("/getIntroduction")
    @ResponseBody
    public Introduction getIntroduction() {
        Introduction introduction = introductionService.getIntroduction();
        introduction.setImage(null);
        return introduction;
    }

    /**
     * 修改当前的公司介绍
     * @param introduction
     * @param file
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public Map<String, String> update(Introduction introduction, @RequestBody MultipartFile file) throws IOException {
        introduction.setImage(file.getBytes());
        Integer i = introductionService.update(introduction);
        if(i > 0) {
            return MapUtil.responseMap("修改成功", "true");
        } else {
            return MapUtil.responseMap("修改失败", "false");
        }

    }

    @RequestMapping("/getImage")
    public void getAvatar(HttpServletResponse response, String uuid) throws IOException {
        System.out.println(uuid);
        Introduction introduction = introductionService.getIntroduction();
        response.setContentType("image/png");
        OutputStream output = response.getOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(introduction.getImage());
        int len;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf)) != -1) {
            output.write(buf, 0, len);
        }
        output.flush();
        output.close();
    }
}
